import { FC } from 'react';
import style from './index.module.scss';
import { Spin } from 'antd';
import { useEditorStore } from '@/store/editor';
import classNames from 'classnames';
import { getComponet } from '@/comon/tools';
import { useCanvasKeyPress } from '@/hooks/useCanvasKeyPress';
import DragContainer from '@/components/drag/DragContainer';
import DragItem from '@/components/drag/DragItem';

interface EditorCanvasProps {
  loading?: boolean;
}

const EditorCanvas: FC<EditorCanvasProps> = (props) => {
  const { loading } = props;
  const { componentList, selectedId, select, dragMove } = useEditorStore();
  const items = componentList.map((item) => ({
    ...item,
    id: item.fe_id!,
  }));
  // 添加快捷键
  useCanvasKeyPress();

  function selectComponent(e: any, id?: string) {
    e.stopPropagation();
    select(id || '');
  }

  function onDragEnd(oldIndex: number, newIndex: number) {
    dragMove(oldIndex, newIndex);
  }

  if (loading) {
    return (
      <div style={{ marginTop: 24, textAlign: 'center' }}>
        <Spin />
      </div>
    );
  }

  const list = componentList
    .filter((info) => info.isHidden === false)
    .map((info) => {
      const wrapperClassname = classNames({
        [style['component-wrapper']]: true,
        [style.selected]: info.fe_id === selectedId,
        [style.lock]: info.isLocked,
      });

      return (
        <DragItem id={info.fe_id!} key={info.fe_id}>
          <div
            className={wrapperClassname}
            onClick={(e) => selectComponent(e, info.fe_id)}
          >
            <div className={style.component}>{getComponet(info)}</div>
          </div>
        </DragItem>
      );
    });

  return (
    <DragContainer items={items} onDragEnd={onDragEnd}>
      <div className={style.canvas}>{list}</div>
    </DragContainer>
  );
};

export default EditorCanvas;
